﻿using Microsoft.AspNetCore.Mvc;
using System.Collections;
using System;
using BP.DA;
using BP.Difference;
using BP.En;
using BP.Sys;
using BP.Tools;
using BP.Web;
using BP.WF.HttpHandler;
using BP.WF;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Web;
using System.Linq;
using System.IO;
using Microsoft.AspNetCore.Http;
using NPOI.SS.Formula.Eval;
using Org.BouncyCastle.Tsp;
using BP.CCBill;
using Org.BouncyCastle.Utilities;
//using Spire.Doc.Fields;
using NPOI.Util;
using BP.WF.Template.Frm;
using System.Diagnostics.CodeAnalysis;
using BP.Template.Printer;
using Microsoft.Extensions.Primitives;
using BP.Sys.Printer;

namespace CCFlow.NetCore.DataUser.API.Controllers
{

    /// <summary>
    /// 应用类型
    /// </summary>
    public class AppModel
    {
        /// <summary>
        /// 单据设计
        /// </summary>
        public const string TemplateDesinger = "TemplateDesinger";
        /// <summary>
        /// 解析器
        /// </summary>
        public const string FrmExcel = "FrmExcel";
        /// <summary>
        /// 单据-excel
        /// </summary>
        public const string MyBillExcel = "MyBillExcel";
        /// <summary>
        /// 单据-word
        /// </summary>
        public const string MyBillWord = "MyBillWord";
        /// <summary>
        /// 打印组件
        /// </summary>
        public const string FrmPrinter = "FrmPrinter";
        /// <summary>
        /// 打印模版设置
        /// </summary>
        public const string PrinterTemplateDesinger = "PrinterTemplateDesinger";

        /// <summary>
        /// 附件预览组件
        /// </summary>
        public const string AthHelper = "AthHelper";
        /// <summary>
        /// Excel工作处理器
        /// </summary>
        public const string MyFlowExcel = "MyFlowExcel";
    }
    [Route("WF/[controller]/[Action]")]
    [ApiController]
    public class VSTOController : ControllerBase
    {
        #region 报表.
        [HttpPost]
        [Consumes("multipart/form-data")]
        public object PrinterTemplateDesinger_FileSave(string token, string templateID)
        {
            IFormFile file = HttpContextHelper.RequestFiles(0);
            BP.WF.Dev2Interface.Port_LoginByToken(token);
            if (file == null || file.Length == 0)
                throw new Exception("err@文件数据bytes没有传递过来.");
            try
            {
                BP.Sys.Printer.PrintTemplate pt = new BP.Sys.Printer.PrintTemplate(templateID);
                 
                string fileName = templateID;

                if (pt.HisPrintFileType == PrintFileType.Excel|| pt.HisPrintFileType == PrintFileType.Word)
                {
                    if (pt.HisPrintFileType == PrintFileType.Excel) {
                        //Excel格式
                        fileName += ".xlsx";
                    }
                    if (pt.HisPrintFileType == PrintFileType.Word)
                    {
                        //Excel格式
                        fileName += ".docx";
                    }

                    string frmVSTOTemplateFilePath = BP.Difference.SystemConfig.PathOfDataUser + "FrmVSTOTemplate/" + fileName;
                    if (System.IO.File.Exists(frmVSTOTemplateFilePath))
                        System.IO.File.Delete(frmVSTOTemplateFilePath);

                    HttpContextHelper.UploadFile(file, frmVSTOTemplateFilePath);
                    using (var memoryStream = new MemoryStream())
                    {
                        file.CopyTo(memoryStream);
                        Byte[] bys = memoryStream.ToArray();
                        DBAccess.SaveBytesToDB(bys, "Sys_FrmPrintTemplate", "MyPK", templateID, "DBFile");
                        return Return_Info(200, "成功", "执行成功.");
                    }
                }
                else
                {
                    return Return_Info(500, "保存文件错误PrinterTemplateDesinger_FileSave:", "");
                }
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, ex.Message, null);
            }
        }

        [HttpGet, HttpPost]
        public object PrinterTemplateDesinger_FileGener(string token, string mypk)
        {
            try
            {
                BP.Sys.Printer.PrintTemplate printer = new BP.Sys.Printer.PrintTemplate(mypk);

                byte[] bytes = null;
                //验证表单类型
                if (printer.HisPrintFileType == PrintFileType.Excel)
                {
                    //Excel格式
                    bytes = printer.GenerFile();
                    return Return_Info(200, "成功", bytes);
                }
                else if (printer.HisPrintFileType == PrintFileType.Word)
                {
                    //Word格式
                    bytes = printer.GenerWordFile();
                    return Return_Info(200, "成功", bytes);
                }
                else {
                    return Return_Info(500, "获取文件错误PrinterTemplateDesinger_FileGener:", "");
                }
                
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, "获取文件错误Designer_FileTemplateGener:", ex.Message);
            }
        }

        [HttpGet, HttpPost]
        public object Printer_FileGener(string token, string mypk)
        {
            try
            {
                BP.Template.Printer.FrmPrintDB printer = new BP.Template.Printer.FrmPrintDB(mypk);

                //string ss = printer.FileExt

                byte[] bytes = null;
                Paras ps = new Paras();
                ps.SQL = "SELECT MyPK,FrmID,FrmName,WorkID,FrmPrintTemplateID,FrmPrintTemplateName,FileExt  FROM sys_frmprintdb  WHERE  MyPK='"+ mypk + "'";                
                DataTable dt_fpd = DBAccess.RunSQLReturnTable(ps);
                if (dt_fpd != null && dt_fpd.Rows.Count > 0) { 
                    DataRow dr_fpd = dt_fpd.Rows[0];
                    string FileExt = dr_fpd["FileExt"].ToString().ToLower();
                    if (FileExt == "xlsx")
                    {
                        //Excel格式
                        bytes = printer.GenerFile();
                        return Return_Info(200, "成功", bytes);
                    }
                    else if (FileExt == "docx")
                    {
                        //Word格式
                        bytes = printer.GenerWordFile();
                        return Return_Info(200, "成功", bytes);
                    }
                    else {
                        return Return_Info(500, "获取文件错误Printer_FileGener:", "");
                    }
                }


                return Return_Info(200, "成功", printer.GenerFile());
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, "获取文件错误Printer_FileGener:", ex.Message);
            }
        }
        #endregion

        #region 表单设计器.
        [HttpGet, HttpPost]
        [Consumes("multipart/form-data")]
        public object Designer_FileTemplateSave(string token, string frmID)
        {
            IFormFile file = HttpContextHelper.RequestFiles(0);
            BP.WF.Dev2Interface.Port_LoginByToken(token);

            try
            {
                if (file == null || file.Length == 0)
                    throw new Exception("err@文件数据bytes没有传递过来.");

                MapData md = new MapData(frmID);

                string fileName = frmID;
                //验证表单类型
                if (md.HisFrmTypeInt == 6)
                {
                    //Excel格式
                    fileName += ".xlsx";
                }
                else if (md.HisFrmTypeInt == 61)
                {
                    //Word格式
                    fileName += ".docx";
                }

                string frmVSTOTemplateFilePath = BP.Difference.SystemConfig.PathOfDataUser + "FrmVSTOTemplate/" + fileName;
                if (System.IO.File.Exists(frmVSTOTemplateFilePath))
                {
                    System.IO.File.Delete(frmVSTOTemplateFilePath);
                }
                HttpContextHelper.UploadFile(file, frmVSTOTemplateFilePath);

                using (var memoryStream = new MemoryStream())
                {
                    file.CopyTo(memoryStream);
                    Byte[] bys = memoryStream.ToArray();
                    DBAccess.SaveBytesToDB(bys, "Sys_MapData", "No", frmID, MapDataAttr.VSTOExcelFile);
                    return Return_Info(200, "成功", "执行成功.");
                }

            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, ex.Message, null);
            }
        }
        /// <summary>
        /// 获得表单模版 
        /// </summary>
        /// <param name="token"></param>
        /// <param name="frmID"></param>
        /// <returns></returns>
        [HttpGet, HttpPost]
        public object Designer_FileTemplateGener(string token, string frmID)
        {
            try
            {
                BP.WF.Dev2Interface.Port_LoginByToken(token);
                byte[] bytes = null;
                MapData md = new MapData(frmID);

                //验证表单类型
                if (md.HisFrmTypeInt == 6)
                {
                    //Excel格式
                    md.ExcelGenerFile(ref bytes);
                    return Return_Info(200, "成功", bytes);
                }
                else if (md.HisFrmTypeInt == 61)
                {
                    //Word格式
                    md.WordGenerFile(ref bytes);
                    return Return_Info(200, "成功", bytes);
                }
                else {
                    return Return_Info(500, "获取文件错误Designer_FileTemplateGener:非vsto表单", "");
                }
               
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, "获取文件错误Designer_FileTemplateGener:", ex.Message);
            }
        }
        /// <summary>
        /// 创建从表
        /// </summary>
        /// <param name="token"></param>
        /// <param name="frmID"></param>
        /// <param name="dtlID"></param>
        /// <param name="dtlName"></param>
        /// <returns></returns>

        [HttpGet, HttpPost]
        public object Designer_CreateDtl(string token, string frmID, string dtlID, string dtlName)
        {
            try
            {
                MapDtl dtl = new MapDtl();
                dtl.No = dtlID;
                if (dtl.RetrieveFromDBSources() == 1)
                    return Return_Info(200, "成功", "err@从表[" + dtlID + "]已经存在.");

                BP.Sys.CCFormAPI.CreateOrSaveDtl(frmID, dtlID, dtlName);
                return Return_Info(200, "成功", "创建成功.");
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, ex.Message, null);
            }
        }
        [HttpGet, HttpPost]
        public object Designer_FrmExcelDataSet(string token, string frmID)
        {
            lock (WF_Comm.frmVSTOTemplateLock)
                BP.WF.Dev2Interface.Port_LoginByToken(token);

            DataSet ds = new DataSet();
            MapData mapData = new MapData(frmID);
            DataTable mapDataTable = mapData.ToDataTableField("Sys_MapData");
            ds.Tables.Add(mapDataTable);

            MapAttrs mapAttrs = new MapAttrs(frmID);
            DataTable mapAttrDataTable = mapAttrs.ToDataTableField("Sys_MapAttr");
            ds.Tables.Add(mapAttrDataTable);

            DataTable mapDtlDataTable = mapData.MapDtls.ToDataTableField("Sys_MapDtl");
            ds.Tables.Add(mapDtlDataTable);

            //加入字段分组信息
            DataTable Sys_GroupField = mapData.GroupFields.ToDataTableField("Sys_GroupField");
            ds.Tables.Add(Sys_GroupField);

            foreach (MapDtl item in mapData.MapDtls)
            {
                MapAttrs mapDtlAttrs = new MapAttrs(item.No);
                DataTable mapDtlAttrDataTable = mapDtlAttrs.ToDataTableField("Sys_MapAttr_" + item.No);
                ds.Tables.Add(mapDtlAttrDataTable);
            }
            return Return_Info(200, "成功", ds);
        }
        #endregion 设计器.

        #region 附件在线预览.
        /// <summary>
        /// 保存附件
        /// </summary>
        /// <param name="token"></param>
        /// <param name="mypk"></param>
        /// <returns></returns>
        [HttpGet, HttpPost]
        public object AthHelper_Save(string token, string mypk)
        {
            try
            {
                IFormFile file = HttpContextHelper.RequestFiles(0);
                BP.WF.Dev2Interface.Port_LoginByToken(token);
                if (file == null || file.Length == 0)
                    throw new Exception("err@文件数据bytes没有传递过来.");

                FrmAttachmentDB frmAttachmentDB = new FrmAttachmentDB(mypk);

                //现将上传的文件转存为临时文件.
                string tempFile = BP.Difference.SystemConfig.PathOfTemp + frmAttachmentDB.MyPK + ".tmp";
                if (System.IO.File.Exists(tempFile))
                    System.IO.File.Delete(tempFile);

                //下载文件.
                HttpContextHelper.UploadFile(file, tempFile);

                //把文件上传上去，覆盖现在的文件数据.
                frmAttachmentDB.GenerFileUpload(tempFile, null, false);

                //删除掉临时文件
                if (System.IO.File.Exists(tempFile) == true)
                    System.IO.File.Delete(tempFile);

                return Return_Info(200, "成功", "更新成功");
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, "失败", ex.Message);
            }
        }
        /// <summary>
        /// 保存公文文件
        /// </summary>
        /// <param name="token"></param>
        /// <param name="nodeId"></param>
        /// <param name="workId"></param>
        /// <returns></returns>
        [HttpGet, HttpPost]
        public object SaveGongWenWord(string token, string nodeId, string workId)
        {

            try
            {
                if (HttpContextHelper.RequestFilesCount < 0 || DataType.IsNullOrEmpty(token) || DataType.IsNullOrEmpty(nodeId))
                {
                    return "err@参数不能为空";
                }
                BP.WF.Dev2Interface.Port_LoginByToken(token);
                IFormFile file = HttpContextHelper.RequestFiles(0);

                byte[] buffer = new byte[file.Length];

                //创建Stream对象，并指向上传文件
                Stream fileStream = file.OpenReadStream();
                //从当前流中读取字节，读入字节数组中
                fileStream.Read(buffer, 0, (int)file.Length);


                Node nd = new Node(int.Parse(nodeId));
                Work wk = nd.HisWork;
                wk.OID = int.Parse(workId);
                wk.SaveBytesToDB(GWDBFile, buffer);

                return "已成功保存到服务器";
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return "err@" + ex.Message;

            }
        }

        /// <summary>
        /// 初始化文件
        /// </summary>
        /// <param name="token"></param>
        /// <param name="frmAttachmentMyPk"></param>
        /// <returns></returns>
        [HttpGet, HttpPost]
        public object AthHelper_Init(string token, string myPK)
        {
            if (DataType.IsNullOrEmpty(myPK))
                return Return_Info(500, "参数不能为空", null);
            try
            {
                //生成文件流
                BP.WF.Dev2Interface.Port_LoginByToken(token);


                FrmAttachmentDB db = new FrmAttachmentDB(myPK);
                string pathfile = db.GenerTempFile(); //下载到一个临时文件.

                byte[] bytes = DataType.ConvertFileToByte(pathfile);
                string base64Str = bytes != null ? Convert.ToBase64String(bytes) : "";

                return Return_Info(200, "成功", bytes);
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, "失败", ex.Message);
            }
        }
        #endregion

        #region 打印在线编辑.
        /// <summary>
        /// 保存附件
        /// </summary>
        /// <param name="token"></param>
        /// <param name="mypk"></param>
        /// <returns></returns>
        [HttpGet, HttpPost]
        public object FrmPrinter_Save(string token, string mypk)
        {
            try
            {
                IFormFile file = HttpContextHelper.RequestFiles(0);
                BP.WF.Dev2Interface.Port_LoginByToken(token);
                if (file == null || file.Length == 0)
                    throw new Exception("err@文件数据bytes没有传递过来.");

                FrmPrintDB frmPrintDB = new FrmPrintDB(mypk);

                //现将上传的文件转存为临时文件.
                string tempFile = BP.Difference.SystemConfig.PathOfTemp + frmPrintDB.MyPK + ".tmp";
                if (System.IO.File.Exists(tempFile))
                    System.IO.File.Delete(tempFile);

                //下载文件.
                HttpContextHelper.UploadFile(file, tempFile);
                DBAccess.SaveFileToDB(tempFile, "Sys_FrmPrintDB", "MyPK", mypk, "DBFile");

                //删除掉临时文件
                if (System.IO.File.Exists(tempFile) == true)
                    System.IO.File.Delete(tempFile);

                return Return_Info(200, "成功", "更新成功");
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, "失败", ex.Message);
            }
        }

        #endregion
        #region 工作流程
        [HttpGet, HttpPost]
        public object MyFlow_Toolbar(string token, Int64 workID)
        {
            try
            {
                //执行登录.
                BP.WF.Dev2Interface.Port_LoginByToken(token);

                GenerWorkFlow gwl = new GenerWorkFlow(workID);
                if (gwl.IsOver == true)
                {

                }

                CCMobile_MyFlow hanlder = new CCMobile_MyFlow();
                hanlder.AddPara("FlowNo", gwl.FlowNo);
                hanlder.AddPara("WorkID", workID.ToString());
                hanlder.AddPara("NodeID", gwl.NodeID.ToString());
                string str = hanlder.InitToolBar();
                // DataTable dataTable = new DataTable();
                return Return_Info(200, "成功", str);
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, ex.Message, null);
            }
        }
        [HttpGet, HttpPost]
        public object MyFlow_Mesage(string token, Int64 workID)
        {
            try
            {
                //执行登录.
                BP.WF.Dev2Interface.Port_LoginByToken(token);

                GenerWorkFlow gwf = new GenerWorkFlow(workID);

                //获得消息.
                DataTable dt = BP.WF.CCFlowAPI.GetFlowAlertMsg(gwf, new Node(gwf.NodeID), gwf.FlowNo, workID, gwf.FID);

                //返回信息.
                return Return_Info(200, "成功", BP.Tools.Json.ToJson(dt));
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, ex.Message, null);
            }
        }

        [HttpGet, HttpPost]
        public object MyFlow_GenerWillReturnNodes(string token, Int64 workID)
        {
            try
            {
                //执行登录.
                BP.WF.Dev2Interface.Port_LoginByToken(token);

                //获得要退回的节点.
                DataTable dt = BP.WF.Dev2Interface.DB_GenerWillReturnNodes(workID);

                return Return_Info(200, "成功", BP.Tools.Json.ToJson(dt));
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, ex.Message, null);
            }
        }
        [HttpGet, HttpPost]
        public object MyFlow_ReturnWork(string token, Int64 workID, int toNodeID, string toEmpNo, string msg, int isBackNode)
        {
            try
            {
                //执行登录.
                BP.WF.Dev2Interface.Port_LoginByToken(token);

                bool _isBackNode = false;
                if (isBackNode == 1)
                    _isBackNode = true;

                //获得要退回的节点.
                var str = BP.WF.Dev2Interface.Node_ReturnWork(workID, toNodeID, toEmpNo, msg, _isBackNode);

                return Return_Info(200, "成功", str);
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, ex.Message, null);
            }
        }
        [HttpGet, HttpPost]
        public object MyFlow_WorkOptInit(string token, Int64 workID, int toNodeID, string mypk)
        {
            try
            {
                //执行登录.
                BP.WF.Dev2Interface.Port_LoginByToken(token);

                GenerWorkFlow gwf = new GenerWorkFlow(workID);
                BP.WF.HttpHandler.WF_WorkOpt opt = new WF_WorkOpt();
                opt.AddPara("WorkID", workID);
                opt.AddPara("NodeID", gwf.NodeID);
                opt.AddPara("ToNodeID", toNodeID);
                opt.AddPara("MyPK", mypk);
                string data = opt.SendWorkOpt_Init();
                return Return_Info(200, "成功", data);
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, ex.Message, null);
            }
        }
        /// <summary>
        /// 发送
        /// </summary>
        /// <param name="token">token</param>
        /// <param name="workID">workID</param>
        /// <param name="toNodeID">到达的节点ID</param>
        /// <param name="toEmps">到达的人员</param>
        /// <returns></returns>
        [HttpGet, HttpPost]
        public object MyFlow_Send(string token, Int64 workID, int toNodeID, string toEmps)
        {
            try
            {
                //执行登录.
                BP.WF.Dev2Interface.Port_LoginByToken(token);

                //执行登录.
                SendReturnObjs objs = BP.WF.Dev2Interface.Node_SendWork(null, workID, toNodeID, toEmps);

                // DataTable dataTable = new DataTable();
                return Return_Info(200, "成功", objs.ToMsgOfText());
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, ex.Message, null);
            }
        }
        [HttpGet, HttpPost]
        public object MyFlow_SendUn(string token, Int64 workID)
        {
            try
            {
                //执行登录.
                BP.WF.Dev2Interface.Port_LoginByToken(token);

                GenerWorkFlow gwf = new GenerWorkFlow(workID);
                //撤销.
                string msg = BP.WF.Dev2Interface.Flow_DoUnSend(gwf.FlowNo, workID);

                // DataTable dataTable = new DataTable();
                return Return_Info(200, "成功", msg);
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, ex.Message, null);
            }
        }
        #endregion 工作流程

        #region MyBill.单据
        /// <summary>
        /// 初始化toolbar内容
        /// </summary>
        /// <param name="token"></param>
        /// <param name="frmID"></param>
        /// <param name="workID">workID</param>
        /// <returns>执行结果</returns>
        [HttpGet, HttpPost]
        public object MyBill_Toolbar(string token, string frmID, Int64 workID)
        {
            try
            {
                //执行登录.
                BP.WF.Dev2Interface.Port_LoginByToken(token);

                //获得工具栏的按钮.
                GenerBill gb = new GenerBill(workID);
                DataTable dt = gb.GenerToolbar();

                return Return_Info(200, "成功", BP.Tools.Json.ToJson(dt));
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, ex.Message, null);
            }
        }


        /// <summary>
        /// 执行归档
        /// </summary>
        /// <param name="token">token</param>
        /// <param name="workID">工作ID</param>
        /// <returns></returns>
        [HttpGet, HttpPost]
        public object MyBill_FrmOver(string token, Int64 workID)
        {
            try
            {
                //执行登录.
                BP.WF.Dev2Interface.Port_LoginByToken(token);
                //执行归档
                BP.CCBill.Dev2Interface.MyBill_SetFrmOver(workID);

                return Return_Info(200, "成功", "执行成功.");
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, ex.Message, null);
            }
        }
        /// <summary>
        /// 撤销归档
        /// </summary>
        /// <param name="token"></param>
        /// <param name="workID"></param>
        /// <returns></returns>
        [HttpGet, HttpPost]
        public object MyBill_ArchiveUn(string token, Int64 workID)
        {
            try
            {
                //执行登录.
                BP.WF.Dev2Interface.Port_LoginByToken(token);

                //执行归档
                BP.CCBill.Dev2Interface.MyBill_ArchiveUn(workID);

                return Return_Info(200, "成功", "执行成功.");
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, ex.Message, null);
            }
        }
        /// <summary>
        /// 撤销归档
        /// </summary>
        /// <param name="token"></param>
        /// <param name="workID">要撤销的workoID</param>
        /// <returns></returns>
        [HttpGet, HttpPost]
        public object MyBill_SetEditing(string token, Int64 workID)
        {
            try
            {
                //执行登录.
                BP.WF.Dev2Interface.Port_LoginByToken(token);

                //执行归档
                BP.CCBill.Dev2Interface.MyBill_SetEditing(workID);

                return Return_Info(200, "成功", "执行成功.");
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, ex.Message, null);
            }
        }


        /// <summary>
        /// 执行删除
        /// </summary>
        /// <param name="token"></param>
        /// <param name="frmID">表单ID</param>
        /// <param name="workID">工作ID</param>
        /// <returns></returns>
        [HttpGet, HttpPost]
        public object MyBill_Delete(string token, string frmID, Int64 workID)
        {
            try
            {
                //执行登录.
                BP.WF.Dev2Interface.Port_LoginByToken(token);

                //执行归档
                BP.CCBill.Dev2Interface.MyBill_Delete(frmID, workID);

                return Return_Info(200, "成功", "执行成功.");
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, ex.Message, null);
            }
        }
        #endregion MyBill.

        #region zp在2024.11.22 整理vsto表单接口.
        /// <summary>
        /// 获得实体信息
        /// </summary>
        /// <param name="token">会话ID</param>
        /// <param name="enName">实体名称</param>
        /// <param name="pkval">主键值</param>
        /// <returns>一行数据</returns>
        [HttpGet, HttpPost]
        public object Entity_Retrieve(string token, string enName, string pkval)
        {
            try
            {
                BP.WF.Dev2Interface.Port_LoginByToken(token);
                Entity en = ClassFactory.GetEn(enName);
                if (en == null)
                    throw new Exception("类EnName=[" + enName + "]拼写不正确,或者不存在.");

                en.PKVal = pkval;
                en.Retrieve();

                DataTable dt = en.ToDataTableField();
                return Return_Info(200, "成功", dt);
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, ex.Message, null);
            }
        }
        /// <summary>
        /// 获得实体信息
        /// </summary>
        /// <param name="token">会话ID</param>
        /// <param name="enName">实体名称</param>
        /// <param name="pkval">主键值</param>
        /// <returns>一行数据</returns>
        [HttpGet, HttpPost]
        public object Entity_RetrieveFromDBSources(string token, string enName, string pkval)
        {
            try
            {
                BP.WF.Dev2Interface.Port_LoginByToken(token);
                Entity en = ClassFactory.GetEn(enName);
                if (en == null)
                    throw new Exception("类EnName=[" + enName + "]拼写不正确,或者不存在.");
                en.PKVal = pkval;
                int i = en.RetrieveFromDBSources();

                DataTable dt = en.ToDataTableField();
                dt.Columns.Add("NumOfRows", typeof(string)); //增加列名,标记查询数量.
                dt.Rows[0]["NumOfRows"] = i; //前端，用于检查是否存在数据.

                return Return_Info(200, "成功", dt);
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, ex.Message, null);
            }
        }
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="token"></param>
        /// <param name="enName"></param>
        /// <returns></returns>
        [HttpGet, HttpPost]
        public object Entity_Init(string token, string enName)
        {
            try
            {
                BP.WF.Dev2Interface.Port_LoginByToken(token);

                //获得 en.
                Entity en = ClassFactory.GetEn(enName);
                if (en == null)
                    throw new Exception("类EnName=[" + enName + "]拼写不正确,或者不存在.");

                //获得数据.
                DataTable dt = en.ToDataTableField();

                ////获得数据.
                //DataTable dt = en.ToEmptyTableField();
                //DataRow dr = dt.NewRow();
                //dt.Rows.Add(dr);
                return Return_Info(200, "成功", dt);
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, ex.Message, null);
            }
        }
        /// <summary>
        /// 实体删除
        /// </summary>
        /// <param name="token"></param>
        /// <param name="enName"></param>
        /// <param name="pkval"></param>
        /// <returns></returns>
        [HttpGet, HttpPost]
        public object Entity_Delete(string token, string enName, string pkval)
        {
            try
            {
                BP.WF.Dev2Interface.Port_LoginByToken(token);

                Entity en = ClassFactory.GetEn(enName);
                if (en == null)
                    throw new Exception("类EnName=[" + enName + "]拼写不正确,或者不存在.");
                en.PKVal = pkval;
                if (en.RetrieveFromDBSources() > 0)
                {
                    en.Delete();
                }
                return Return_Info(200, "成功", 1);
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, ex.Message, null);
            }
        }
        /// <summary>
        /// 执行更新.
        /// </summary>
        /// <param name="token"></param>
        /// <param name="enName"></param>
        /// <param name="pkval"></param>
        /// <param name="row"></param>
        /// <returns></returns>
        [HttpGet, HttpPost]
        public object Entity_Update(string token, string enName, string pkval, string row)
        {
            try
            {
                BP.WF.Dev2Interface.Port_LoginByToken(token);

                Entity en = ClassFactory.GetEn(enName);
                if (en == null)
                    throw new Exception("类EnName=[" + enName + "]拼写不正确,或者不存在.");
                en.PKVal = pkval;
                en.Retrieve();

                // row 是一个json数据，怎么把json转化为 ht.
                Attrs attrs = en.EnMap.Attrs;
                DataTable dt = BP.Tools.Json.ToDataTable(row); //获得数据.
                foreach (DataColumn dc in dt.Columns)
                {
                    string key = null;
                    foreach (Attr attr in attrs)
                    {
                        if (dc.ColumnName.ToLower().Equals(attr.Key.ToLower()) == true)
                        {
                            key = attr.Key;
                        }
                    }
                    if (key == null)
                        continue;
                    en.SetValByKey(key, dt.Rows[0][dc.ColumnName]);
                }

                en.Update();
                return Return_Info(200, "成功", 1);
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, ex.Message, null);
            }
        }
        /// <summary>
        /// 插入
        /// </summary>
        /// <param name="token"></param>
        /// <param name="enName"></param>
        /// <param name="pkval"></param>
        /// <param name="row"></param>
        /// <returns></returns>
        [HttpGet, HttpPost]
        public object Entity_Insert(string token, string enName, string pkval, string row)
        {
            try
            {
                BP.WF.Dev2Interface.Port_LoginByToken(token);
                Entity en = ClassFactory.GetEn(enName);
                if (en == null)
                    throw new Exception("类EnName=[" + enName + "]拼写不正确,或者不存在.");

                // row 是一个json数据，怎么把json转化为 ht.
                Attrs attrs = en.EnMap.Attrs;
                DataTable dt = BP.Tools.Json.ToDataTable(row); //获得数据.
                foreach (DataColumn dc in dt.Columns)
                {
                    string key = null;
                    foreach (Attr attr in attrs)
                    {
                        if (dc.ColumnName.ToLower().Equals(attr.Key.ToLower()) == true)
                            key = attr.Key;
                    }
                    if (key == null)
                        continue;
                    en.SetValByKey(key, dt.Rows[0][dc.ColumnName]);
                }

                en.PKVal = pkval;
                en.Insert();
                return Return_Info(200, "成功", 1);
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, ex.Message, null);
            }
        }
        /// <summary>
        /// 获得实体信息
        /// </summary>
        /// <param name="token">token</param>
        /// <param name="ensName">实体类名</param>
        /// <param name="key1">字段名称</param>
        /// <param name="val1">字段值</param>
        /// <param name="key2">字段名称</param>
        /// <param name="val2">字段值</param>
        /// <returns>集合</returns>
        [HttpGet, HttpPost]
        public object Entities_Retrieve(string token, string ensName, string key1, string val1, [AllowNull] string key2, [AllowNull] string val2, string orderBy)
        {
            try
            {
                BP.WF.Dev2Interface.Port_LoginByToken(token);
                Entities ens = ClassFactory.GetEns(ensName);
                if (ens == null)
                    throw new Exception("类 ensName=[" + ensName + "]拼写不正确,或者不存在.");
                if (val1 == null)
                    throw new Exception("属性[" + key1 + "]不能为空.");

                if (key2 == null)
                    ens.Retrieve(key1, val1, orderBy);
                else
                    ens.Retrieve(key1, val1, key2, val2, orderBy);

                DataTable dt = ens.ToDataTableField();
                return Return_Info(200, "成功", dt);
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, ex.Message, null);
            }
        }
        [HttpGet, HttpPost]
        public object Entities_RetrieveAll(string token, string ensName)
        {
            try
            {
                BP.WF.Dev2Interface.Port_LoginByToken(token);
                Entities ens = ClassFactory.GetEns(ensName);
                if (ens == null)
                    throw new Exception("类 ensName=[" + ensName + "]拼写不正确,或者不存在.");

                ens.RetrieveAll();

                DataTable dt = ens.ToDataTableField();
                return Return_Info(200, "成功", dt);
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, ex.Message, null);
            }
        }
        #endregion 创建

        #region 通用功能
        /// <summary>
        /// office插件和wps插件编辑公文相关接口
        /// </summary>

        public const string GWDBFile = "GWDBFile";

        /// <summary>
        /// office插件和wps插件编辑文件相关接口
        /// </summary>
        public const string DBFile = "DBFile";
        /// <summary>
        /// 返回信息格式:此数据格式可以根据自己的需要来定义.
        /// </summary>
        /// <param name="code">代码:200=成功，500=失败.</param>
        /// <param name="msg">消息:错误的信息.</param>
        /// <param name="data">数据:相关的json格式的数据.</param>
        /// <returns></returns>
        public static object Return_Info(int code, string msg, object data)
        {
            Hashtable ht = new Hashtable();
            ht.Add("code", code);
            ht.Add("message", msg);
            ht.Add("data", data);
            return JsonConvert.SerializeObject(ht);
        }
        /// <summary>
        /// 获得版本
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>

        [HttpGet, HttpPost]
        public object Gener_Ver(string token)
        {
            try
            {
                return Return_Info(200, "成功", "1.1.0.7");
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, ex.Message, null);
            }
        }
        /// <summary>
        /// 获得用户信息
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpGet, HttpPost]
        public object Gener_WebUser(string token)
        {
            try
            {
                BP.WF.Dev2Interface.Port_LoginByToken(token);

                Hashtable ht = new Hashtable();
                ht.Add("No", WebUser.No);
                ht.Add("Name", WebUser.Name);
                ht.Add("DeptNo", WebUser.DeptNo);
                ht.Add("DeptName", WebUser.DeptName);
                ht.Add("OrgNo", WebUser.OrgNo);
                ht.Add("OrgName", WebUser.OrgName);

                string json = BP.Tools.Json.ToJson(ht);
                return Return_Info(200, "成功", json);
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, ex.Message, null);
            }
        }
        /// <summary>
        /// 获取表单模版
        /// </summary>
        /// <param name="token"></param>
        /// <param name="frmID"></param>
        /// <returns></returns>
        [HttpGet, HttpPost]
        public object Gener_FileTemplate(string token, string frmID)
        {
            try
            {
                BP.WF.Dev2Interface.Port_LoginByToken(token);
                MapData md;
                //如果是一个实体类.
                if (frmID.Contains("BP."))
                {
                    // 执行map同步.
                    Entities ens = ClassFactory.GetEns(frmID + "s");
                    Entity en = ens.GetNewEntity;
                    md = en.DTSMapToSys_MapData();
                }
                else
                {
                    md = new MapData(frmID);
                }

                byte[] bytes = null;

                md.ExcelGenerFile(ref bytes);

                string base64Str = bytes != null ? Convert.ToBase64String(bytes) : "";

                return Return_Info(200, "执行成功", base64Str);
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, "获得Excel模板文件时出现异常，调用接口[GenerTemplateFile]\n" + ex.Message, "");
            }
        }
        /// <summary>
        /// 返回类型
        /// </summary>
        /// <param name="token"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpGet, HttpPost]
        public object Gener_DBType(string token, string name)
        {
            try
            {
                List<string> arrayList = new List<string>();
                arrayList.Add(name);
                string json = BP.Sys.CCFormAPI.GenerDataTypeByCHName(arrayList);
                return Return_Info(200, "成功", json);
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, ex.Message, null);
            }
        }

        [HttpGet, HttpPost]
        public object Gener_PinYin(string token, string name, bool flag)
        {
            try
            {
                //Dev2Interface.Port_LoginByToken(token);
                //此处为字段中文转拼音，设置为最大20个字符，edited by liuxc,2017-9-25
                string str = BP.Sys.CCFormAPI.ParseStringToPinyinField(name, flag, true, 20);
                return Return_Info(200, "成功", str);
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, ex.Message, null);
            }
        }

        #endregion 通用功能

        /// <summary>
        /// 获得Excel文件
        /// </summary>
        /// <param name="token"></param>
        /// <param name="frmID"></param>
        /// <returns></returns>
        [HttpGet, HttpPost]
        public object GenerTemplateFile(string token, string frmID)
        {
            try
            {
                BP.WF.Dev2Interface.Port_LoginByToken(token);

                MapData md;
                //如果是一个实体类.
                if (frmID.Contains("BP."))
                {
                    // 执行map同步.
                    Entities ens = ClassFactory.GetEns(frmID + "s");
                    Entity en = ens.GetNewEntity;
                    md = en.DTSMapToSys_MapData();
                }
                else
                {
                    md = new MapData(frmID);
                }

                byte[] bytes = null;
                md.ExcelGenerFile(ref bytes);
                string base64Str = bytes != null ? Convert.ToBase64String(bytes) : "";

                return Return_Info(200, "执行成功", base64Str);
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, "获得Excel模板文件时出现异常，调用接口[GenerTemplateFile]\n" + ex.Message, "");
            }
        }

        /// <summary>
        /// 获得Excel文件
        /// </summary>
        /// <param name="token"></param>
        /// <param name="frmID"></param>
        /// <param name="pkValue"></param>
        /// <returns></returns>
        [HttpGet, HttpPost]
        public object GenerExcelFile(string token, string frmID, string pkValue)
        {
            try
            {
                BP.WF.Dev2Interface.Port_LoginByToken(token);

                byte[] bytes = null;
                MapData md;
                //如果是一个实体类.
                if (frmID.Contains("BP."))
                {
                    // 执行map同步.
                    Entities ens = ClassFactory.GetEns(frmID + "s");
                    Entity en = ens.GetNewEntity;
                    md = en.DTSMapToSys_MapData();
                }
                else
                {
                    md = new MapData(frmID);
                }
                //创建excel表单描述，让其保存到excel表单指定的字段里, 扩展多个表单映射同一张表.
                MapFrmExcel mfe = new MapFrmExcel(md.No);

                md.ExcelGenerFileEntity(pkValue, ref bytes, mfe.DBSave);

                if (bytes != null)
                {
                    //转为字符
                    string docStr = Convert.ToBase64String(bytes);
                    return Return_Info(200, "执行成功", docStr);
                }
                else
                {
                    return Return_Info(404, "没有获取到文件流", "");
                }
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, ex.Message, "");
            }
        }
        /// <summary>
        /// 初始化表单数据
        /// </summary>
        /// <param name="token"></param>
        /// <param name="frmID"></param>
        /// <param name="pkVal"></param>
        /// <param name="atParas"></param>
        /// <returns></returns>
        [HttpGet, HttpPost]
        public object Frm_InitFrmDataSet(string token, string frmID, string pkVal, string atParas)
        {
            //让他登录.
            BP.WF.Dev2Interface.Port_LoginByToken(token);

            //解析这个表单.
            try
            {
                DataSet ds = BP.WF.CCFormAPI.GenerDBForVSTOExcelFrmModel(frmID, pkVal, atParas);
                return Return_Info(200, "执行成功", Json.ToJson(ds));
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, ex.Message, null);
            }
        }
        [HttpGet, HttpPost]
        public object Frm_SFTableDB(string token, string sfTablePK)
        {
            try
            {
                SFTable sf = new SFTable(sfTablePK);
                DataTable dt = sf.GenerHisDataTable();
                return Return_Info(200, "执行成功", dt);
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, "执行失败:" + ex.Message, ex.Message);
            }
        }
        /// <summary>
        /// VSTO,执行保存Excel主表数据 
        /// </summary>
        /// <param name="token"></param>
        /// <param name="frmID"></param>
        /// <param name="pkValue"></param>
        /// <param name="mainTableAtParas"></param>
        [HttpGet, HttpPost]
        public object Frm_SaveExcelFileMainTable([FromBody] RequestData requestData, string token, string frmID, string pkValue)
        {
            try
            {
                //执行登录.
                BP.WF.Dev2Interface.Port_LoginByToken(token);

                Hashtable ht = BP.Tools.Json.ToHashtable(requestData.data);

                #region 求主表的主键类型.
                string pkType = null;
                string sql = "SELECT KeyOfEn FROM Sys_MapAttr WHERE FK_MapData='" + frmID + "' AND KeyOfEn='OID' ";
                if (DBAccess.RunSQLReturnTable(sql).Rows.Count == 1)
                    pkType = "OID";

                if (pkType == null)
                {
                    sql = "SELECT KeyOfEn FROM Sys_MapAttr WHERE FK_MapData='" + frmID + "' AND KeyOfEn='MyPK' ";
                    if (DBAccess.RunSQLReturnTable(sql).Rows.Count == 1)
                        pkType = "MyPK";
                }

                if (pkType == null)
                    pkType = "No";
                #endregion 求主表的主键类型.

                #region 处理EntityMyPK 类型的实体保存。
                if (pkType.Equals("MyPK") == true)
                {
                    /* 具有MyPK 的实体，为了简便判断. */
                    GEEntityMyPK wk = new GEEntityMyPK(frmID, pkValue);
                    wk.ResetDefaultVal();

                    if (ht != null)
                    {
                        foreach (string str in ht.Keys)
                        {
                            if (wk.Row.ContainsKey(str))
                                wk.SetValByKey(str, ht[str]);
                            else
                                wk.Row.Add(str, ht[str]);
                        }
                    }
                    wk.MyPK = pkValue;
                    // 保存实体.
                    wk.Save();
                }
                #endregion 处理 EntityMyPK 类型的实体保存。

                #region 处理 EntityNoName 类型的实体保存。
                if (pkType.Equals("No") == true)
                {
                    /* 具有MyPK 的实体，为了简便判断. */
                    GEEntityNoName wk = new GEEntityNoName(frmID);
                    wk.ResetDefaultVal();
                    wk.SetValByKey("No", pkValue);
                    wk.RetrieveFromDBSources();

                    if (ht != null)
                    {

                        foreach (string str in ht.Keys)
                        {
                            if (wk.Row.ContainsKey(str))
                                wk.SetValByKey(str, ht[str]);
                            else
                                wk.Row.Add(str, ht[str]);
                        }
                    }
                    wk.SetValByKey("No", pkValue);
                    // 保存实体.
                    wk.Save();
                }
                #endregion 处理 EntityMyPK 类型的实体保存。


                #region 处理 EntityOID 类型的实体保存。
                if (pkType.Equals("OID") == true)
                {
                    GEEntityOID wk = new GEEntityOID(frmID, pkValue);
                    wk.ResetDefaultVal();
                    wk.SetValByKey("BillState", 1);

                    if (ht != null)
                    {
                        foreach (string str in ht.Keys)
                        {
                            if (wk.Row.ContainsKey(str))
                                wk.SetValByKey(str, ht[str]);
                            else
                                wk.Row.Add(str, ht[str]);
                        }
                    }
                    wk.OID = long.Parse(pkValue);
                    //保存.
                    wk.Save();
                }
                #endregion 处理 EntityOID 类型的实体保存。
                return Return_Info(200, "执行成功", "执行成功.");
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, "执行失败", ex.Message);
            }
        }
        /// <summary>
        /// 执行保存
        /// </summary>
        /// <param name="token"></param>
        /// <param name="frmID">表单ID</param>
        /// <param name="workID">工作ID</param>
        /// <param name="AppID">工作ID</param>
        /// <returns></returns>
        [HttpGet, HttpPost]
        public object Frm_FileSave(string token, string frmID, Int64 workID, string AppID)
        {
            IFormFile file = HttpContextHelper.RequestFiles(0);
            BP.WF.Dev2Interface.Port_LoginByToken(token);
            if (file == null || file.Length == 0)
                throw new Exception("err@文件数据bytes没有传递过来.");
            try
            {
                MapData md = new MapData(frmID);
                if (AppID.Equals(AppModel.MyBillExcel) || AppID.Equals(AppModel.MyBillWord))
                {
                    BP.CCBill.Dev2Interface.MyBill_SetEditing(workID);
                    BP.CCBill.Dev2Interface.SaveBillWork(workID);
                }

                using (var memoryStream = new MemoryStream())
                {
                    file.CopyTo(memoryStream);
                    Byte[] bys = memoryStream.ToArray();
                    DBAccess.SaveBytesToDB(bys, md.PTable, "OID", workID, "VSTOExcelFile");
                    return Return_Info(200, "成功", "执行成功.");
                }
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, ex.Message, null);
            }
        }
        /// <summary>
        /// 获得单据文件
        /// </summary>
        /// <param name="token"></param>
        /// <param name="frmID"></param>
        /// <param name="workID"></param>
        /// <returns></returns>
        [HttpGet, HttpPost]
        public object FrmExcel_FileGener(string token, string frmID, Int64 workID)
        {
            try
            {
                BP.WF.Dev2Interface.Port_LoginByToken(token);

                byte[] bytes = null;
                MapData md = new MapData(frmID);

                //创建excel表单描述，让其保存到excel表单指定的字段里, 扩展多个表单映射同一张表.
                MapFrmExcel mfe = new MapFrmExcel(frmID);
                md.ExcelGenerFileEntity(workID.ToString(), ref bytes, MapDataAttr.VSTOExcelFile);
                if (bytes != null)
                {
                    string docStr = Convert.ToBase64String(bytes);
                    return Return_Info(200, "执行成功", docStr);
                }
                return Return_Info(404, "没有获取到文件流", "");
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, ex.Message, "");
            }
        }

        /// <summary>
        /// 获得单据文件Word
        /// </summary>
        /// <param name="token"></param>
        /// <param name="frmID"></param>
        /// <param name="workID"></param>
        /// <returns></returns>
        [HttpGet, HttpPost]
        public object FrmWord_FileGener(string token, string frmID, Int64 workID)
        {
            try
            {
                BP.WF.Dev2Interface.Port_LoginByToken(token);

                byte[] bytes = null;
                MapData md = new MapData(frmID);

                MapFrmWord mfe = new MapFrmWord(frmID);
                md.WordGenerFileEntity(workID.ToString(), ref bytes, MapDataAttr.VSTOExcelFile);
                if (bytes != null)
                {
                    string docStr = Convert.ToBase64String(bytes);
                    return Return_Info(200, "执行成功", docStr);
                }
                return Return_Info(404, "没有获取到文件流", "");
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, ex.Message, "");
            }
        }
        /// <summary>
        /// 执行保存Excel从表数据.
        /// </summary>
        /// <param name="requestData"></param>
        /// <returns></returns>
        [HttpGet, HttpPost]
        public object Frm_SaveExcelFileDtls([FromBody] RequestData requestData)
        {
            try
            {
                #region 1.参数登录检查.
                if (DataType.IsNullOrEmpty(requestData.token) || DataType.IsNullOrEmpty(requestData.frmID) || DataType.IsNullOrEmpty(requestData.pkValue))
                    return Return_Info(500, "参数不能为空", null);

                DataSet dsDtlsNew = JsonConvert.DeserializeObject<DataSet>(requestData.data);
                BP.WF.Dev2Interface.Port_LoginByToken(requestData.token); //登录.
                #endregion 1.参数登录检查.


                MapDtls dtls = new MapDtls(requestData.frmID);
                foreach (MapDtl mapDtl in dtls)
                {
                    if (dsDtlsNew.Tables.Contains(mapDtl.No) == false)
                        continue;

                    GEDtls gEDtls = new GEDtls(mapDtl.No);

                    //接收的table数据
                    DataTable dataTable = dsDtlsNew.Tables[mapDtl.No];

                    QueryObject queryObject = new QueryObject(gEDtls);
                    queryObject.AddWhere(mapDtl.RefPK, requestData.pkValue);
                    DataTable oldDataTable = queryObject.DoQueryToTable();

                    List<string> oldOidList = oldDataTable.AsEnumerable().Select(row => row.Field<long>("OID").ToString()).Distinct().ToList();
                    foreach (DataRow dr in dataTable.Rows)
                    {
                        //在原有数据基础上删除不存在的oid数据
                        if (oldOidList.Count > 0 && oldOidList.Contains(dr["OID"].ToString()))
                        {
                            oldOidList.RemoveAll(x => x == dr["OID"].ToString());
                        }

                        GEDtl daDtl = gEDtls.GetNewEntity as GEDtl;
                        daDtl.OID = int.Parse(dr["OID"].ToString());
                        int count = daDtl.RetrieveFromDBSources();
                        daDtl.RDT = DataType.CurrentDateTime;

                        //更新字段值
                        foreach (DataColumn dc in dataTable.Columns)
                        {
                            //设置属性.
                            daDtl.SetValByKey(dc.ColumnName, dr[dc.ColumnName]);
                        }
                        if (count > 0)
                        {
                            daDtl.Update();
                        }
                        else
                        {
                            daDtl.RefPK = requestData.pkValue;
                            daDtl.InsertAsOID(DBAccess.GenerOID(daDtl.EnMap.PhysicsTable));
                        }
                    }

                    if (oldOidList.Count > 0)
                    {
                        Paras ps = new Paras();
                        ps.SQL = "DELETE FROM " + mapDtl.PTable + " WHERE OID in ( " + string.Join(",", oldOidList) + ")";
                        //ps.Add("V", string.Join(",", oldOidList));
                        DBAccess.RunSQL(ps);
                        //    string deleteSql = "DELETE FROM " + mapDtl.PTable + " WHERE OID in ( " + string.Join(",", oldOidList) + ")";
                        //DBAccess.RunSQL(deleteSql);
                    }
                }
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, ex.Message, null);
            }

            return Return_Info(200, "执行成功", null);
        }

        /// <summary>
        /// 生成vsto模式的数据
        /// </summary>
        /// <param name="token"></param>
        /// <param name="frmID"></param>
        /// <param name="pkValue"></param>
        /// <param name="atParas"></param>
        /// <returns></returns>
        [HttpGet, HttpPost]
        public object GenerDBForVSTOExcelFrmModel(string token, string frmID, string pkValue, string atParas)
        {
            //让他登录.
            BP.WF.Dev2Interface.Port_LoginByToken(token);

            //解析这个表单.
            try
            {
                DataSet ds = BP.WF.CCFormAPI.GenerDBForVSTOExcelFrmModel(frmID, pkValue, atParas);

                return Return_Info(200, "执行成功", Json.ToJson(ds));
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, ex.Message, null);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="workID"></param>
        /// <param name="createReportType"></param>
        /// <returns></returns>
        [HttpGet, HttpPost]
        public object GetReportImagesData(long workID, string createReportType)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(createReportType))
                    return null;

                string dbStr = SystemConfig.AppCenterDBVarStr;
                Paras ps = new Paras();


                switch (createReportType)
                {
                    case "1":
                        ps.SQL = "SELECT FileFullName,FileExts,MyPK,FileName  FROM Sys_FrmAttachmentDB  WHERE  RefPKVal=" + dbStr + "RefPKVal";
                        ps.Add(FrmAttachmentDBAttr.RefPKVal, workID);
                        break;
                    case "2":
                        ps.SQL = "SELECT FileFullName,FileExts,MyPK,FileName  FROM Sys_FrmAttachmentDB  WHERE " +
                                 "RefPKVal in(SELECT WorkID FROM WF_GenerWorkFlow WHERE PWORKID=" + dbStr + "PWORKID)";
                        ps.Add("PWORKID", workID);
                        break;
                    default:
                        break;
                }
                DataTable dt = DBAccess.RunSQLReturnTable(ps);

                List<ReportImage> reImgsList = new List<ReportImage>();
                foreach (DataRow dr in dt.Rows)
                {
                    string fileFullName = dr["FileFullName"].ToString();
                    if (System.IO.File.Exists(fileFullName))
                    {
                        FileStream fs = new FileStream(fileFullName, FileMode.Open);
                        long size = fs.Length;
                        byte[] bytes = new byte[size];
                        fs.Read(bytes, 0, bytes.Length);
                        fs.Close();

                        reImgsList.Add(new ReportImage
                        {
                            ext = dr["FileExts"].ToString(), //frmDB.FileExts,
                            fileName = dr["FileName"].ToString(), //frmDB.FileName,
                            bytesData = Convert.ToBase64String(bytes),
                            mypk = dr["MyPK"].ToString() //frmDB.MyPK
                        });
                    }
                }

                return Return_Info(200, "执行成功", LitJson.JsonMapper.ToJson(reImgsList));
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, ex.Message, null);
            }
        }

        /// <summary>
        /// 保存一个文件
        /// </summary>
        /// <param name="token"></param>
        /// <param name="frmID"></param>
        /// <param name="nodeID"></param>
        /// <param name="workID"></param>
        /// <param name="base64Data"></param>
        /// <param name="guid"></param>
        [HttpGet, HttpPost]
        public object SaveFrmAth(string token, string frmID, int nodeID, long workID, string base64Data, string guid)
        {
            try
            {
                BP.WF.Dev2Interface.Port_LoginByToken(token);
                MapData md = new MapData(frmID);
                FrmAttachments aths = new FrmAttachments(frmID);
                if (aths.Count == 0)
                {
                    BP.Sys.CCFormAPI.CreateOrSaveAthMulti(md.No, "Ath", "附件");
                    aths = new FrmAttachments(frmID);
                }
                FrmAttachment ath = aths[0] as FrmAttachment;

                //把文件写入.
                string rootPath = ath.SaveTo;
                string fileName = guid + "." + System.Drawing.Imaging.ImageFormat.Jpeg.ToString();
                string filePath = rootPath + fileName;
                if (System.IO.File.Exists(filePath) == true)
                    System.IO.File.Delete(filePath);

                byte[] byt = Convert.FromBase64String(base64Data);

                DataType.WriteFile(filePath, byt);

                FileInfo info = new FileInfo(filePath);
                FrmAttachmentDB dbUpload = new FrmAttachmentDB();
                dbUpload.MyPK = guid;
                dbUpload.NodeID = nodeID;
                dbUpload.Sort = null;
                dbUpload.FrmID = ath.FrmID;
                dbUpload.FK_FrmAttachment = ath.MyPK;

                dbUpload.FileExts = info.Extension;
                dbUpload.FileFullName = filePath;
                dbUpload.FileName = fileName;
                dbUpload.FileSize = info.Length;
                dbUpload.RDT = DataType.CurrentDateTimess;
                dbUpload.Rec = WebUser.No;
                dbUpload.RecName = WebUser.Name;
                dbUpload.RefPKVal = workID.ToString();

                dbUpload.UploadGUID = guid;
                dbUpload.DirectSave();
                return Return_Info(200, "成功", null);
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, ex.Message, null);
            }

        }

        /// <summary>
        /// 获得附件byte
        /// </summary>
        /// <param name="token"></param>
        /// <param name="frmAttachmentMyPk"></param>
        /// <returns></returns>
        [HttpGet, HttpPost]
        public object GenerFrmAttachmentByte(string token, string frmAttachmentMyPk)
        {
            try
            {

                lock (WF_Comm.pblock)
                {
                    //生成文件流
                    byte[] bytes = null;
                    BP.WF.Dev2Interface.Port_LoginByToken(token);

                    if (DataType.IsNullOrEmpty(frmAttachmentMyPk))
                    {
                        return Return_Info(500, "参数不能为空", null);
                    }

                    FrmAttachmentDB frmAttachmentDB = new FrmAttachmentDB();

                    frmAttachmentDB.MyPK = frmAttachmentMyPk;
                    int count = frmAttachmentDB.Retrieve();

                    if (count == 0)
                    {
                        return Return_Info(500, "文件不存在", null);
                    }
                    FrmAttachment frmAttachment = new FrmAttachment();
                    frmAttachment.MyPK = frmAttachmentDB.FK_FrmAttachment;
                    frmAttachment.Retrieve();

                    //临时文件
                    string temFilePath = "";

                    //获取配置项是否加密
                    bool fileEncrypt = SystemConfig.isEnableAthEncrypt;

                    //获取此文件是否加密
                    bool isEncrypt = frmAttachmentDB.GetParaBoolen("IsEncrypt");
                    if (frmAttachment.AthSaveWay == AthSaveWay.IISServer)
                    {

                        temFilePath = frmAttachmentDB.FileFullName + ".tmp";
                        if (fileEncrypt == true && isEncrypt == true)
                        {


                            if (System.IO.File.Exists(temFilePath) == true)
                                System.IO.File.Delete(temFilePath);
                            EncHelper.DecryptDES(frmAttachmentDB.FileFullName, temFilePath);
                        }
                        else
                        {
                            bytes = DataType.ConvertFileToByte(frmAttachmentDB.FileFullName);
                        }
                    }

                    if (frmAttachment.AthSaveWay == AthSaveWay.FTPServer)
                    {
                        //下载文件到临时位置
                        string orignalFile = frmAttachmentDB.GenerTempFile(frmAttachment.AthSaveWay);
                        temFilePath = orignalFile + ".temp";
                        if (fileEncrypt == true && isEncrypt == true)
                        {
                            EncHelper.DecryptDES(orignalFile, temFilePath);
                            //将下载的临时文件删除掉
                            if (System.IO.File.Exists(orignalFile) == true)
                                System.IO.File.Delete(orignalFile);
                        }
                        else
                            temFilePath = orignalFile;
                    }
                    if (frmAttachment.AthSaveWay == AthSaveWay.DB)
                    {
                        //加密文件处理
                        if (fileEncrypt == true && isEncrypt == true)
                        {
                            //根据流生成初试源文件
                            string orignalFile = frmAttachmentDB.GenerTempFile(frmAttachment.AthSaveWay);
                            temFilePath = orignalFile + ".temp";

                            //根据初试源文件生成解密后的文件
                            EncHelper.DecryptDES(orignalFile, temFilePath);
                            if (System.IO.File.Exists(orignalFile) == true)
                                System.IO.File.Delete(orignalFile);
                        }
                        else
                        {
                            //不是加密文件直接读取流
                            bytes = frmAttachmentDB.GetFileFromDB(DBFile, null);
                        }
                    }
                    if (bytes == null)
                    {
                        bytes = DataType.ConvertFileToByte(temFilePath);
                    }
                    string base64Str = bytes != null ? Convert.ToBase64String(bytes) : "";

                    //将临时文件删掉
                    if (System.IO.File.Exists(temFilePath))
                    {
                        System.IO.File.Delete(temFilePath);
                    }
                    Hashtable hs = new Hashtable();
                    hs.Add("bytes", bytes);
                    hs.Add("name", frmAttachmentDB.FileName);
                    return Return_Info(200, "成功", hs);
                }
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, ex.Message, null);
            }
            return Return_Info(500, "文件不存在", null);
        }
        /// <summary>
        /// wps获得公文
        /// </summary>
        /// <param name="token"></param>
        /// <param name="mypk"></param>
        /// <param name="flowNo"></param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GenerGongWenTrackByte")]
        public object GenerGongWenTrackByteWPS(string token, string mypk, int flowNo)
        {
            try
            {
                //生成文件流
                byte[] bytes = null;
                if (DataType.IsNullOrEmpty(token) || DataType.IsNullOrEmpty(mypk) || flowNo == 0)
                    return Return_Info(500, "参数不能为空", "");

                BP.WF.Dev2Interface.Port_LoginByToken(token);
                string tableTrack = "ND" + flowNo + "Track";
                bytes = DBAccess.GetByteFromDB(tableTrack, "MyPk", mypk, GWDBFile);

                if (bytes == null || bytes.Length == 0)
                {

                    return Return_Info(500, "历史公文不存在", "");
                }
                HttpContextHelper.DownLoadFileByBytes(bytes, DBAccess.GenerGUID() + ".docx");
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, ex.Message, "");
            }
            return Return_Info(500, "历史公文不存在", "");
        }
        #region vsto 组件功能.

        #region Old API
        /// <summary>
        /// 获取VSTO插件版本号
        /// </summary>
        /// <returns></returns>
        [HttpGet, HttpPost]
        public object GetVstoCCFormWordExtensionVersion()
        {
            return Return_Info(200, "执行成功", "1.1.0.4");
        }
        #endregion Old API
        /// <summary>
        /// 初始化公文组件
        /// </summary>
        /// <param name="token">登录人员的信息</param>
        /// <param name="workID">工作ID</param>
        /// <returns>执行结果</returns>
        [HttpGet, HttpPost]
        public object VSTOWord_GongWen_Init(string token, long workID)
        {
            //根据token登录.
            Port_GenerToken(token);
            try
            {
                GenerWorkFlow gwf = new GenerWorkFlow(workID);

                //是否可以查看
                if (BP.WF.Dev2Interface.Flow_IsCanViewTruck(gwf.FlowNo, workID, WebUser.No) == false)
                {
                    string msg = "err@您无权查看该工作,";
                    msg += "\t\n如下情况可以查看该工作.";
                    msg += "\t\n1. 该流程发起人, 审批人，抄送人，可以查看.";
                    msg += "\t\n2. 默认与发起人是同一个部门的人可以查看.";
                    msg += "\t\n3. 二级管理员可以查看本组织的工作.";
                    msg += "\t\n4. 超级管理员可以查看.";
                    msg += "\t\n5. 流程属性的权限控制设置权限的人可以查看.";
                    msg += "\t\n6. 如果该流程的数据，任何人都可以查看，请在流程属性里设置权限控制，任何人可见.";
                    throw new Exception(msg);
                }

                //是否可以操作
                if (BP.WF.Dev2Interface.Flow_IsCanDoCurrentWork(workID, WebUser.No) == false)
                {
                    string msg = "err@您无权处理该工作.";
                    throw new Exception(msg);
                }

                //是否已经有了模板文件
                if (BP.WF.Dev2Interface.Flow_IsHaveDocFile(workID) == false)
                {
                    string msg = "err@没有上传公文模板，请您上传模板后重试.";
                    throw new Exception(msg);
                }
                return Return_Info(200, "执行成功", gwf.ToJson());
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, "失败", ex.Message);
            }
        }
        /// <summary>
        /// 创建公文
        /// </summary>
        /// <param name="token">Token</param>
        /// <param name="workID">WorkID</param>
        /// <param name="templateFileNo">模板主键</param>
        /// <returns></returns>
        [HttpGet, HttpPost]
        public object VSTOWord_GongWen_Create(string token, string workID, string templateFileNo)
        {
            //根据token登录.
            Port_GenerToken(token);
            try
            {
                GenerWorkFlow gwf = new GenerWorkFlow(workID);

                //选择一个模板来创建
                string dbstr = SystemConfig.AppCenterDBVarStr;
                Paras ps = new Paras();
                ps.SQL = "SELECT * FROM WF_Part a WHERE  MyPK=" + dbstr + "MyPK ";
                ps.Add("MyPK", templateFileNo);
                DataTable dt = DBAccess.RunSQLReturnTable(ps);

                if (dt.Rows.Count == 0)
                {
                    throw new Exception("err@没有找到公文模板.请检查WF_Part表,主键 [MyPK] = [" + templateFileNo + "] ,如没有数据请上传公文模板.");
                }

                //拿到文件路径
                string filePath = dt.Rows[0]["MyFilePath"].ToString();

                //转为二进制
                var bytes = DataType.ConvertFileToByte(filePath);

                //文件二进制存储到业务表PTable的DocFile字段
                Flow fl = new Flow(gwf.FlowNo);
                DBAccess.SaveBytesToDB(bytes, fl.PTable, "OID", workID, "DocFile");

                return Return_Info(200, "创建成功", "");
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, "失败", ex.Message);
            }
        }

        /// <summary>
        /// 获得公文
        /// </summary>
        /// <param name="token"></param>
        /// <param name="workID"></param>
        /// <param name="nodeID"></param>
        /// <param name="gongWenTemplateFile"></param>
        /// <returns></returns>
        [HttpGet, HttpPost]
        public object GenerGongWenByte(string token, int workID, int nodeID, string gongWenTemplateFile)
        {
            try
            {
                //
                lock (WF_Comm.gongWenWordTemplateLock)
                {
                    //生成文件流
                    byte[] bytes = null;
                    if (DataType.IsNullOrEmpty(token))
                    {
                        return Return_Info(500, "参数不能为空", null);
                    }
                    BP.WF.Dev2Interface.Port_LoginByToken(token);
                    Node nd = new Node(nodeID);
                    Work wk = nd.HisWork;
                    wk.OID = workID;
                    wk.RetrieveFromDBSources();
                    bytes = wk.GetFileFromDB(GWDBFile, "");

                    string fileName = "空白模板.docx";
                    if (!DataType.IsNullOrEmpty(gongWenTemplateFile))
                    {
                        fileName = HttpUtility.UrlDecode(gongWenTemplateFile, Encoding.UTF8);
                    }
                    if (bytes == null || bytes.Length == 0)
                    {

                        string frmVSTOTemplateFilePath = SystemConfig.PathOfDataUser + "DocFlow\\" + fileName;
                        if (System.IO.File.Exists(frmVSTOTemplateFilePath))
                        {
                            bytes = DataType.ConvertFileToByte(frmVSTOTemplateFilePath);
                        }
                        else
                        {
                            return Return_Info(500, "初始化模板文件不存在", null);
                        }


                    }
                    string base64Str = bytes != null ? Convert.ToBase64String(bytes) : "";
                    return Return_Info(200, "成功", bytes);
                }
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, ex.Message, null);
            }
        }

        /// <summary>
        /// 获得doc文件
        /// </summary>
        /// <param name="token"></param>
        /// <param name="workID"></param>
        /// <returns></returns>
        [HttpGet, HttpPost]
        public object VSTOWord_GongWen_GetDocFile(string token, long workID)
        {
            //根据token登录.
            Port_GenerToken(token);
            try
            {
                GenerWorkFlow gwf = new GenerWorkFlow(workID);
                Flow fl = new Flow(gwf.FlowNo);
                //获取文件流
                byte[] bytes = DBAccess.GetByteFromDB(fl.PTable, "OID", workID.ToString(), "DocFile");

                return Return_Info(200, "执行成功", bytes);
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, "失败", ex.Message);
            }
        }

        /// <summary>
        /// 获得pdf文件
        /// </summary>
        /// <param name="token"></param>
        /// <param name="workID"></param>
        /// <returns></returns>
        [HttpGet, HttpPost]
        public object VSTOWord_GongWen_GetPDFFile(string token, long workID)
        {
            //根据token登录.
            Port_GenerToken(token);
            try
            {
                return Return_Info(200, "暂缓", "xxxx");
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, "失败", ex.Message);
            }
        }

        /// <summary>
        /// 保存公文
        /// </summary>
        /// <param name="token">Token</param>
        /// <param name="workID">WorkID</param>
        /// <param name="bytes">文件流</param>
        /// <returns></returns>
        [HttpGet, HttpPost]
        public object VSTOWord_GongWen_SaveFile(string token, long workID, byte[] bytes)
        {
            //根据token登录.
            Port_GenerToken(token);
            try
            {
                GenerWorkFlow gwf = new GenerWorkFlow(workID);
                //文件二进制存储到业务表PTable的DocFile字段
                Flow fl = new Flow(gwf.FlowNo);
                DBAccess.SaveBytesToDB(bytes, fl.PTable, "OID", workID, "DocFile");

                return Return_Info(200, "公文保存成功", "");
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, "失败", ex.Message);
            }
        }

        #region wps功能
        /// <summary>
        /// wps获得公文文件流
        /// </summary>
        /// <param name="token"></param>
        /// <param name="workId"></param>
        /// <param name="fkNodeId"></param>
        /// <param name="response"></param>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost, HttpGet]
        public object GenerGongWenByteWPS(string token, int workId, int fkNodeId, string gongWenTemplateFile)
        {
            try
            {
                //生成文件流
                byte[] bytes = null;
                if (DataType.IsNullOrEmpty(token) || workId == 0 || fkNodeId == 0)
                {
                    return Return_Info(500, "参数不能为空", "");
                }
                BP.WF.Dev2Interface.Port_LoginByToken(token);
                Node nd = new Node(fkNodeId);
                Work wk = nd.HisWork;
                wk.OID = workId;
                wk.RetrieveFromDBSources();

                bytes = wk.GetFileFromDB(GWDBFile, "");

                string fileName = "空白模板.docx";
                if (!DataType.IsNullOrEmpty(gongWenTemplateFile))
                {
                    fileName = HttpUtility.UrlDecode(gongWenTemplateFile, Encoding.UTF8);
                }
                if (bytes == null || bytes.Length == 0)
                {

                    string frmVSTOTemplateFilePath = SystemConfig.PathOfDataUser + "DocFlow/" + fileName;

                    if (System.IO.File.Exists(frmVSTOTemplateFilePath))
                    {
                        bytes = DataType.ConvertFileToByte(frmVSTOTemplateFilePath);

                    }
                    else
                    {
                        return Return_Info(500, "初始化模板文件不存在", "");
                    }
                }
                HttpContextHelper.DownLoadFileByBytes(bytes, DBAccess.GenerGUID() + ".docx");
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, ex.Message, "");
            }
            return Return_Info(500, "公文不存在", "");
        }

        /// <summary>
        /// WPS上传公文
        /// </summary>
        /// <param name="token"></param>
        /// <param name="workId"></param>
        /// <param name="fkNodeId"></param>
        /// <returns></returns>
        [HttpGet, HttpPost]
        public object SaveGongWenWordWPS(string token, int workId, int fkNodeId)
        {
            try
            {
                if (HttpContextHelper.RequestFilesCount < 0 || DataType.IsNullOrEmpty(token) || workId == 0 || fkNodeId == 0)
                {
                    return Return_Info(500, "参数不能为空", "");
                }
                BP.WF.Dev2Interface.Port_LoginByToken(token);
                IFormFile file = HttpContextHelper.RequestFiles(0);
                BP.WF.Dev2Interface.Port_LoginByToken(token);
                // 二进制数组
                byte[] bytes = new byte[file.Length];

                //创建Stream对象，并指向上传文件
                Stream fileStream = file.OpenReadStream();
                //从当前流中读取字节，读入字节数组中
                fileStream.Read(bytes, 0, (int)file.Length);

                Node nd = new Node(fkNodeId);
                Work wk = nd.HisWork;
                wk.OID = workId;
                int i = wk.RetrieveFromDBSources();
                if (i == 0)
                {
                    throw new Exception("该流程的表单数据不存在");

                }
                wk.SaveBytesToDB(GWDBFile, bytes);
                return "File uploaded successfully";
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, ex.Message, "");
            }
        }


        /// <summary>
        /// WPS获得附件字节
        /// </summary>
        /// <param name="token"></param>
        /// <param name="frmAttachmentMyPk"></param>
        /// <returns></returns>
        [HttpGet, HttpPost]
        public object GenerFrmAttachmentByteWPS(string token, string frmAttachmentMyPk)
        {
            try
            {
                lock (WF_Comm.pblock)
                {
                    //生成文件流
                    byte[] bytes = null;
                    if (DataType.IsNullOrEmpty(frmAttachmentMyPk) || DataType.IsNullOrEmpty(token))
                    {
                        return Return_Info(500, "参数不能为空", "");
                    }
                    BP.WF.Dev2Interface.Port_LoginByToken(token);

                    FrmAttachmentDB frmAttachmentDB = new FrmAttachmentDB();

                    frmAttachmentDB.setMyPK(frmAttachmentMyPk);
                    int count = frmAttachmentDB.Retrieve();

                    if (count == 0)
                    {
                        return Return_Info(500, "文件不存在", "");
                    }
                    FrmAttachment frmAttachment = new FrmAttachment();
                    frmAttachment.setMyPK(frmAttachmentDB.FK_FrmAttachment);
                    frmAttachment.Retrieve();

                    //临时文件
                    string temFilePath = "";

                    //获取配置项是否加密
                    bool fileEncrypt = SystemConfig.isEnableAthEncrypt;

                    //获取此文件是否加密
                    bool isEncrypt = frmAttachmentDB.GetParaBoolen("IsEncrypt");
                    if (frmAttachment.AthSaveWay == AthSaveWay.IISServer)
                    {

                        temFilePath = frmAttachmentDB.FileFullName + ".tmp";
                        if (fileEncrypt == true && isEncrypt == true)
                        {
                            if (System.IO.File.Exists(temFilePath) == true)
                            {
                                System.IO.File.Delete(temFilePath);
                            }
                            EncHelper.EncryptDES(frmAttachmentDB.FileFullName, temFilePath);
                        }
                        else
                        {
                            bytes = DataType.ConvertFileToByte(frmAttachmentDB.FileFullName);
                        }
                    }

                    if (frmAttachment.AthSaveWay == AthSaveWay.FTPServer)
                    {
                        //下载文件到临时位置
                        string orignalFile = frmAttachmentDB.GenerTempFile(frmAttachment.AthSaveWay);
                        temFilePath = orignalFile + ".temp";
                        if (fileEncrypt == true && isEncrypt == true)
                        {
                            EncHelper.DecryptDES(frmAttachmentDB.FileFullName, temFilePath);

                            //将下载的临时文件删除掉
                            if (System.IO.File.Exists(orignalFile))
                            {
                                System.IO.File.Delete(orignalFile);
                            }

                        }
                        else
                            temFilePath = orignalFile;
                    }
                    if (frmAttachment.AthSaveWay == AthSaveWay.DB)
                    {

                        //加密文件处理
                        if (fileEncrypt == true && isEncrypt == true)
                        {
                            //根据流生成初试源文件
                            string orignalFile = frmAttachmentDB.GenerTempFile(frmAttachment.AthSaveWay);
                            temFilePath = orignalFile + ".temp";
                            byte[] bytesEncrypt = frmAttachmentDB.GetFileFromDB(DBFile, null);
                            if (bytesEncrypt == null || bytesEncrypt.Length == 0)
                            {
                                throw new Exception("文件不存在");
                            }

                            //根据初试源文件生成解密后的文件
                            EncHelper.DecryptDES(orignalFile, temFilePath);
                            if (System.IO.File.Exists(orignalFile))
                            {
                                System.IO.File.Delete(orignalFile);
                            }
                        }
                        else
                        {
                            //不是加密文件直接读取流
                            bytes = frmAttachmentDB.GetFileFromDB(GWDBFile, null);
                        }
                    }

                    if (bytes == null)
                    {
                        bytes = DataType.ConvertFileToByte(temFilePath);
                    }

                    HttpContextHelper.DownLoadFileByBytes(bytes, frmAttachmentDB.FileName);
                }
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, ex.Message, "");
            }
            return Return_Info(500, "文件不存在", "");

        }
        /// <summary>
        /// wps保存附件
        /// </summary>
        /// <param name="token"></param>
        /// <param name="frmAttachmentMyPk"></param>
        /// <returns></returns>
        [HttpGet, HttpPost]
        public object SaveFrmAttachmentWPS(string token, string frmAttachmentMyPk)
        {
            try
            {
                lock (WF_Comm.pblock)
                {
                    if (HttpContextHelper.RequestFilesCount < 0 || DataType.IsNullOrEmpty(token) || DataType.IsNullOrEmpty(frmAttachmentMyPk))
                    {
                        return Return_Info(500, "参数不能为空", "");
                    }
                    IFormFile file = HttpContextHelper.RequestFiles(0);
                    BP.WF.Dev2Interface.Port_LoginByToken(token);

                    FrmAttachmentDB frmAttachmentDB = new FrmAttachmentDB();

                    frmAttachmentDB.setMyPK(frmAttachmentMyPk);
                    int count = frmAttachmentDB.Retrieve();
                    if (count == 0)
                    {
                        return Return_Info(500, "文件不存在", "");
                    }
                    FrmAttachment frmAttachment = new FrmAttachment();
                    frmAttachment.setMyPK(frmAttachmentDB.FK_FrmAttachment);
                    frmAttachment.Retrieve();

                    //获取配置项是否加密
                    bool fileEncrypt = SystemConfig.isEnableAthEncrypt;
                    string tempFile = "";
                    //获取此文件是否加密
                    bool isEncrypt = frmAttachmentDB.GetParaBoolen("IsEncrypt");

                    if (frmAttachment.AthSaveWay == AthSaveWay.IISServer)
                    {
                        if (fileEncrypt == true && isEncrypt == true)
                        {
                            //现将上传的文件转存为临时文件
                            tempFile = SystemConfig.PathOfTemp + frmAttachmentDB.MyPK + ".tmp";
                            if (System.IO.File.Exists(tempFile))
                            {
                                System.IO.File.Delete(tempFile);
                            }

                            //将上传的文件转为临时文件
                            HttpContextHelper.UploadFile(file, tempFile);

                            //将原始文件删除掉
                            if (System.IO.File.Exists(frmAttachmentDB.FileFullName))
                            {
                                System.IO.File.Delete(frmAttachmentDB.FileFullName);
                            }

                            //对临时文件进行加密并输出成新文件
                            EncHelper.EncryptDES(tempFile, frmAttachmentDB.FileFullName);
                        }
                        else
                        {
                            //将原始文件删除掉然后保存新文件
                            if (System.IO.File.Exists(frmAttachmentDB.FileFullName))
                            {
                                System.IO.File.Delete(frmAttachmentDB.FileFullName);
                            }
                            HttpContextHelper.UploadFile(file, frmAttachmentDB.FileFullName);
                        }
                    }

                    //数据库存储
                    if (frmAttachment.AthSaveWay == AthSaveWay.DB)
                    {
                        //将上传的文件存储为临时文件
                        tempFile = SystemConfig.PathOfTemp + frmAttachmentDB.MyPK + ".tmp";
                        if (System.IO.File.Exists(tempFile))
                        {
                            System.IO.File.Delete(tempFile);
                        }
                        //将将上传的文件存为临时文件
                        HttpContextHelper.UploadFile(file, tempFile);
                        if (fileEncrypt == true && isEncrypt == true)
                        {


                            //声明加密的文件路径
                            string tempEncryptFile = tempFile + ".encryptTemp";
                            if (System.IO.File.Exists(tempEncryptFile))
                            {
                                System.IO.File.Delete(tempEncryptFile);
                            }

                            //根据初试源文件生成加密后的文件
                            EncHelper.EncryptDES(tempFile, tempEncryptFile);

                            //保存流到数据库
                            frmAttachmentDB.SaveFileToDB(DBFile, tempEncryptFile);

                            //删除掉临时加密后的文件
                            if (System.IO.File.Exists(tempEncryptFile))
                            {
                                System.IO.File.Delete(tempEncryptFile);
                            }
                            if (System.IO.File.Exists(tempFile))
                            {
                                System.IO.File.Delete(tempFile);
                            }

                        }
                        else
                        {
                            frmAttachmentDB.SaveFileToDB(DBFile, tempFile);
                        }
                    }

                    if (frmAttachment.AthSaveWay == AthSaveWay.FTPServer)
                    {
                        //将上传的文件存储为临时文件
                        tempFile = SystemConfig.PathOfTemp + frmAttachmentDB.MyPK + ".tmp";
                        if (System.IO.File.Exists(tempFile))
                        {
                            System.IO.File.Delete(tempFile);//删除临时文件

                        }
                        HttpContextHelper.UploadFile(file, tempFile);
                        BP.FtpConnection ftpconn = null;
                        try
                        {

                            ftpconn = new BP.FtpConnection(SystemConfig.FTPServerIP,
                                          SystemConfig.FTPServerPort,
                                          SystemConfig.FTPUserNo, SystemConfig.FTPUserPassword);
                        }
                        catch
                        {
                            throw new Exception("err@FTP连接失败请检查账号,密码，端口号是否正确");
                        }
                        //2024_03//ND501//b93c100d-bc04-4cd5-ba74-32169f57da23.xlsx 拆分路径
                        string[] strsOld = frmAttachmentDB.FileFullName.Split(new string[] { "//" }, 0);

                        //判断目录年月是否存在.
                        if (ftpconn.DirectoryExist(strsOld[0]) == false)
                            ftpconn.CreateDirectory(strsOld[0]);
                        ftpconn.SetCurrentDirectory(strsOld[0]);

                        //判断目录是否存在.
                        if (ftpconn.DirectoryExist(strsOld[1]) == false)
                            ftpconn.CreateDirectory(strsOld[1]);

                        //设置当前目录，为操作的目录。
                        ftpconn.SetCurrentDirectory(strsOld[1]);

                        string newFileName = DBAccess.GenerGUID() + "." + frmAttachmentDB.FileExts;
                        //对路径重新生成guid名称避免ftp缓存
                        frmAttachmentDB.FileFullName = strsOld[0] + "//" + strsOld[1] + "//" + newFileName;
                        frmAttachmentDB.Update();

                        //新文件存在的话也删除掉
                        if (ftpconn.FileExist(newFileName))
                        {
                            ftpconn.DeleteFile(newFileName);
                        }
                        //加密文件的情况下
                        if (fileEncrypt == true && isEncrypt == true)
                        {
                            string tmpEncrypt = SystemConfig.PathOfTemp + frmAttachmentDB.MyPK + ".encryptTmp";
                            HttpContextHelper.UploadFile(file, tempFile);
                            EncHelper.EncryptDES(tempFile, tmpEncrypt);//加密

                            ftpconn.PutFile(tmpEncrypt, newFileName);

                            //删除掉加密的临时文件
                            if (System.IO.File.Exists(tmpEncrypt) == true)
                                System.IO.File.Delete(tmpEncrypt);
                        }
                        else
                        {
                            ftpconn.PutFile(tempFile, newFileName);
                        }
                        //将原始文件删除掉
                        if (ftpconn.FileExist(strsOld[2]))
                        {
                            ftpconn.DeleteFile(strsOld[2]);
                        }
                        ftpconn.Close();
                        ftpconn = null;
                    }
                    if (System.IO.File.Exists(tempFile))
                    {
                        System.IO.File.Delete(tempFile);
                    }
                }

                return "File uploaded successfully";
            }
            catch (Exception ex)
            {
                BP.DA.Log.DebugWriteException(ex);
                return Return_Info(500, ex.Message, "");
            }
        }
        #endregion

        /// <summary>
        /// 根据Token值验证登录
        /// </summary>
        /// <param name="token"></param>
        protected void Port_GenerToken(string token)
        {
            BP.WF.Dev2Interface.Port_LoginByToken(token);
        }
        public class ReportImage
        {
            public string ext;
            public string fileName;
            public string bytesData;
            public string mypk;
        }
    }
    #endregion
}
